package frontend.components.base;

import frontend.components.other.UserInputCallableAction;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.extensions.markup.html.form.DateTextField;
import org.apache.wicket.extensions.yui.calendar.DatePicker;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.ResourceModel;

import java.util.Date;

public class DatePickerComponent<M> extends Panel {

    public DatePickerComponent(String propertyId, String labelResourceKey, M model) {
        this(propertyId, labelResourceKey, model, null);
    }

    public DatePickerComponent(String propertyId, String labelResourceKey, M model, final UserInputCallableAction<Date> onSelectAction) {
        super(propertyId);
        Label label = new Label("label", new ResourceModel(labelResourceKey));
        final DateTextField dateTextField = new DateTextField("datePicker", new PropertyModel<Date>(model, propertyId));
        dateTextField.add(new AjaxFormComponentUpdatingBehavior("onchange") {
            @Override
            protected void onUpdate(AjaxRequestTarget target) {
                if (onSelectAction != null) {
                    Date selectedValue = dateTextField.getModelObject();
                    onSelectAction.call(target, selectedValue);
                }
            }
        });
        DatePicker datePicker = new DatePicker()
        {
            @Override
            protected String getAdditionalJavaScript()
            {
                return "${calendar}.cfg.setProperty(\"navigator\",true,false); ${calendar}.render();";
            }
        };
        datePicker.setShowOnFieldClick(true);
        datePicker.setAutoHide(true);
        dateTextField.add(datePicker);
        add(label, dateTextField);
        setOutputMarkupId(true);
    }
}
